
#include "participantsheet.h"

#include <QFile>
#include <QTextStream>

ParticipantSheet::ParticipantSheet()
{
    mRecordCount = 0;
}

ParticipantSheet::~ParticipantSheet()
{
}

void ParticipantSheet::addParticipant(Participant* participant)
{
    mParticipants.append(participant);
    mRecordCount++;
    emit participantsChanged();
}

void ParticipantSheet::changeParticipant(int row, Participant* participant)
{
    removeParticipant(row);
    insertParticipant(row, participant);
    emit participantsChanged();
}

void ParticipantSheet::insertParticipant(int row, Participant* participant)
{
    mParticipants.insert(row, participant);
    mRecordCount++;
    emit participantsChanged();
}

void ParticipantSheet::removeParticipant(int row)
{
    qDebug("Removing %d", row);
    mParticipants.removeAt(row);
    mRecordCount--;
    emit participantsChanged();
}

void ParticipantSheet::moveParticipantUp(int row)
{
    qDebug("Move participant up %d", row);
    int size = mParticipants.size();
    if (row > 0 && row < size)
        mParticipants.swap(row, row-1);
    emit participantsChanged();
}

void ParticipantSheet::moveParticipantDown(int row)
{
    int size = mParticipants.size();
    if (row < size - 2 && row > 0)
        mParticipants.swap(row, row+1);
    emit participantsChanged();
}

Participant* ParticipantSheet::getParticipant(int row)
{
    Participant* item = 0;
    if (row >= 0 && row < mParticipants.size())
        item = mParticipants.at(row);
    return item;
}

Participant* ParticipantSheet::getLastParticipant()
{
    Participant* participant = 0;
    if (mParticipants.size() > 0)
        participant =  getParticipant(mParticipants.size()-1);
    return participant;
}

void ParticipantSheet::saveFile(const QString& fileName)
{
    QFile file(fileName);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    for (int row = 0; row < mParticipants.size(); row++)
    {
        Participant* item = mParticipants.at(row);
        out << item->bib() << "\t"
            << item->name() << "\t"
            << item->age() << "\t"
            << item->genderStr() << "\t"
            << item->origin() << "\t"
            << item->member() << "\t"
            << item->hidden() << "\n";
    }
    file.close();
}

QList<Participant*> ParticipantSheet::shownParticipants()
{
    QList<Participant*> participants;
    for (int row = 0; row < mParticipants.size(); row++)
    {
        Participant* item = mParticipants.at(row);
        if (!item->isHidden())
            participants.append(item);
    }
    return participants;
}

